//
//  NSObject+Common.m
//  FDPublic
//
//  Created by 刘伟 on 15/6/19.
//  Copyright (c) 2015年 timShadow. All rights reserved.
//

#import "NSObject+Common.h"

#define kToastDuration     1

@implementation NSObject (Common)


//显示失败提示
- (void)showErrorMsg:(NSString *)msg{
    [self hideProgress];
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[self currentView] animated:YES];
    hud.userInteractionEnabled = NO;
    hud.bezelView.style = MBProgressHUDBackgroundStyleSolidColor;
    hud.bezelView.color = [UIColor colorFromHexCode:@"#1f2124" andAlpha:0.85];
    hud.mode = MBProgressHUDModeCustomView;
    
    
//    NSRegularExpression *numberRegular = [NSRegularExpression regularExpressionWithPattern:@"[A-Za-z]" options:NSRegularExpressionCaseInsensitive error:nil];
//
//    NSInteger count = [numberRegular numberOfMatchesInString:msg?:@"" options:NSMatchingReportProgress range:NSMakeRange(0, msg.length)];
    
    
    if (!msg || [msg isEqualToString:@""] /*|| count > 0*/)
    {
        msg = @"加载失败，请稍后再试";
    }
    
    hud.label.text = msg;
    hud.label.numberOfLines = 0;
    if (DEVICE_IS_IPHONE5||DEVICE_IS_IPHONE4) {
        hud.label.font = [UIFont systemFontOfSize:15];
    }
    else
    {
        hud.label.font = [UIFont systemFontOfSize:16];
    }
    hud.label.textColor = [UIColor colorFromHexCode:@"ffffff"];
    hud.margin = 15.f;
    hud.bezelView.size = CGSizeMake(161, 120);
    hud.minSize = CGSizeMake(127, 120);
    hud.width = 200;
    hud.height = 120;
    hud.center = CGPointMake([self currentView].center.x, [self currentView].center.y - 100);
    
    hud.removeFromSuperViewOnHide = YES;
    
    [hud hideAnimated:YES afterDelay:2];
}

//显示失败提示
- (void)showError:(NSError *)error{
    [self hideProgress];
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[self currentView] animated:YES];
    hud.userInteractionEnabled = NO;
    hud.bezelView.style = MBProgressHUDBackgroundStyleSolidColor;
    hud.bezelView.color = [UIColor colorFromHexCode:@"#1f2124" andAlpha:0.85];
    hud.mode = MBProgressHUDModeCustomView;
    
    NSString* errResponseData = [[NSString alloc] initWithData:(NSData*)error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] encoding:NSUTF8StringEncoding];
    
    NSHTTPURLResponse *response = error.userInfo[AFNetworkingOperationFailingURLResponseErrorKey];
    
    NSLog(@"%ld",response.statusCode);
    NSDictionary *responseHeader = response.allHeaderFields;
    
    NSDictionary *errResponseDataJson = [CSDNTool dictionaryWithJsonString:errResponseData];

    NSString *msg = @"";
    
    if (response.statusCode == 403) {
        if ([responseHeader.allKeys containsObject:@"x-ca-error-code"]) {
            NSString *errorCode = [responseHeader objectForKey:@"x-ca-error-code"];
            if ([errorCode containsString:@"A403JT"] || [errorCode containsString:@"A403JE"]) {
                msg = @"登录失效，请重新登录";
            }
        }
    }else{
        if (errResponseDataJson) {
            if ([errResponseDataJson[@"code"]integerValue] == 403001) {
                msg = @"手机时间异常，请将时间设置正确";
            }
            else if ([errResponseDataJson[@"code"]integerValue] == 403004) {
                msg = @"请到App Store升级最新版本";
            }else if ([errResponseDataJson[@"code"] integerValue] == 400) {
                NSString *message = errResponseDataJson[@"msg"];
                if ([message isValid]) {
                    msg = message;
                }else{
                    msg = error.userInfo[NSLocalizedDescriptionKey];
                }
            }
            else
            {
                msg = error.userInfo[NSLocalizedDescriptionKey];
            }
        }
        else
        {
            msg = error.userInfo[NSLocalizedDescriptionKey];
        }
    }
    
    
    
    if (!msg || [msg isEqualToString:@""] /*|| count > 0*/)
    {
        msg = @"加载失败，请稍后再试";
    }
    
    hud.label.text = msg;
    hud.label.numberOfLines = 0;
    if (DEVICE_IS_IPHONE5||DEVICE_IS_IPHONE4) {
        hud.label.font = [UIFont systemFontOfSize:15];
    }
    else
    {
        hud.label.font = [UIFont systemFontOfSize:16];
    }
    hud.label.textColor = [UIColor colorFromHexCode:@"ffffff"];
    hud.margin = 16.f;
    hud.bezelView.size = CGSizeMake(161, 120);
    hud.minSize = CGSizeMake(127, 120);
    hud.width = 200;
//    hud.height = 120;
    hud.center = CGPointMake([self currentView].center.x, [self currentView].center.y - 50);

    
    
    hud.removeFromSuperViewOnHide = YES;
    
    [hud hideAnimated:YES afterDelay:2];
}

//显示失败提示
- (void)showErrorMsgDescription:(NSString *)msg
{
    [self hideProgress];
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[self currentView] animated:YES];
    hud.userInteractionEnabled = NO;
    hud.bezelView.style = MBProgressHUDBackgroundStyleSolidColor;
    hud.bezelView.color = [UIColor colorFromHexCode:@"#1f2124" andAlpha:0.85];
    hud.mode = MBProgressHUDModeCustomView;
    hud.label.text = msg;
    hud.label.numberOfLines = 0;
    hud.customView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"failure"]];
    hud.customView.size = CGSizeMake(36, 36);
    if (DEVICE_IS_IPHONE5||DEVICE_IS_IPHONE4) {
        hud.label.font = [UIFont systemFontOfSize:15];
    }
    else
    {
        hud.label.font = [UIFont systemFontOfSize:16];
    }
    hud.label.textColor = [UIColor colorFromHexCode:@"ffffff"];
    hud.margin = 15.f;
    hud.bezelView.size = CGSizeMake(161, 116);
    hud.minSize = CGSizeMake(127, 116);
    hud.center = CGPointMake([self currentView].center.x, [self currentView].center.y - 50);
    
    hud.removeFromSuperViewOnHide = YES;
    
    [hud hideAnimated:YES afterDelay:3];
}

//显示成功提示
- (void)showSuccessMsg:(NSString *)msg{
    [self hideProgress];
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[self currentView] animated:YES];
    hud.userInteractionEnabled = NO;
    hud.bezelView.style = MBProgressHUDBackgroundStyleSolidColor;
    hud.bezelView.color = [UIColor colorFromHexCode:@"#1f2124" andAlpha:0.85];
    hud.mode = MBProgressHUDModeCustomView;
    hud.label.text = msg.description;
    hud.label.numberOfLines = 0;
    hud.customView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"success"]];
    hud.customView.size = CGSizeMake(36, 36);
    if (DEVICE_IS_IPHONE5||DEVICE_IS_IPHONE4) {
        hud.label.font = [UIFont systemFontOfSize:15];
    }
    else
    {
        hud.label.font = [UIFont systemFontOfSize:16];
    }
    hud.label.textColor = [UIColor colorFromHexCode:@"ffffff"];
    hud.margin = 15.f;
    hud.bezelView.size = CGSizeMake(161, 116);
    hud.minSize = CGSizeMake(127, 116);
    hud.center = CGPointMake([self currentView].center.x, [self currentView].center.y - 100);
    
    hud.removeFromSuperViewOnHide = YES;
    
    [hud hideAnimated:YES afterDelay:3];
}

//显示忙
- (void)showProgress{
    MBProgressHUD *progressHUD = [MBProgressHUD showHUDAddedTo:[self currentView] animated:YES];
    [progressHUD hideAnimated:YES afterDelay:kToastDuration];
}

//隐藏提示
- (void)hideProgress{
    [MBProgressHUD hideHUDForView:[self currentView] animated:YES];
}

- (UIView *)currentView{
    UIViewController *controller = [[[UIApplication sharedApplication] keyWindow] rootViewController];
    
    if ([controller isKindOfClass:[UITabBarController class]]) {
        controller = [(UITabBarController *)controller selectedViewController];
    }
    if([controller isKindOfClass:[UINavigationController class]]) {
        controller = [(UINavigationController *)controller visibleViewController];
    }
    if (!controller) {
        return [UIApplication sharedApplication].keyWindow;
    }
    return controller.view;
}

#pragma mark - 邮箱校验
+(BOOL)checkForEmail:(NSString *)email{
    
    NSString *regEx = @"^([a-zA-Z0-9_\\-\\.\\+]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,10}|[0-9]{1,3})(\\]?)$";
    return [self baseCheckForRegEx:regEx data:email];
}

#pragma mark - 验证手机号
+(BOOL)checkForMobilePhoneNo:(NSString *)mobilePhone{
    
    NSString *regEx = @"^1[3|4|5|7|8][0-9]\\d{8}$";
    return [self baseCheckForRegEx:regEx data:mobilePhone];
}
#pragma mark - 验证电话号
+(BOOL)checkForPhoneNo:(NSString *)phone{
    NSString *regEx = @"^(\\d{3,4}-)\\d{7,8}$";
    return [self baseCheckForRegEx:regEx data:phone];
}

#pragma mark - 身份证号验证
+ (BOOL) checkForIdCard:(NSString *)idCard{
    
    NSString *regEx = @"\\d{14}[[0-9],0-9xX]";
    return [self baseCheckForRegEx:regEx data:idCard];
}
#pragma mark - 密码校验
+(BOOL)checkForPasswordWithShortest:(NSInteger)shortest longest:(NSInteger)longest password:(NSString *)pwd{
    NSString *regEx =[NSString stringWithFormat:@"^[a-zA-Z0-9]{%ld,%ld}+$", shortest, longest];
    return [self baseCheckForRegEx:regEx data:pwd];
}

//----------------------------------------------------------------------

#pragma mark - 由数字和26个英文字母组成的字符串
+ (BOOL) checkForNumberAndCase:(NSString *)data{
    NSString *regEx = @"^[A-Za-z0-9]+$";
    return [self baseCheckForRegEx:regEx data:data];
}

#pragma mark - 小写字母
+(BOOL)checkForLowerCase:(NSString *)data{
    NSString *regEx = @"^[a-z]+$";
    return [self baseCheckForRegEx:regEx data:data];
}

#pragma mark - 大写字母
+(BOOL)checkForUpperCase:(NSString *)data{
    NSString *regEx = @"^[A-Z]+$";
    return [self baseCheckForRegEx:regEx data:data];
}
#pragma mark - 26位英文字母
+(BOOL)checkForLowerAndUpperCase:(NSString *)data{
    NSString *regEx = @"^[A-Za-z]+$";
    return [self baseCheckForRegEx:regEx data:data];
}

#pragma mark - 特殊字符
+ (BOOL) checkForSpecialChar:(NSString *)data{
    NSString *regEx = @"[^%&',;=?$\x22]+";
    return [self baseCheckForRegEx:regEx data:data];
}

#pragma mark - 只能输入数字
+ (BOOL) checkForNumber:(NSString *)number{
    NSString *regEx = @"^[0-9]*$";
    return [self baseCheckForRegEx:regEx data:number];
}

#pragma mark - 校验只能输入n位的数字
+ (BOOL) checkForNumberWithLength:(NSString *)length number:(NSString *)number{
    NSString *regEx = [NSString stringWithFormat:@"^\\d{%@}$", length];
    return [self baseCheckForRegEx:regEx data:number];
}


#pragma mark - 私有方法
/**
 *  基本的验证方法
 *
 *  @param regEx 校验格式
 *  @param data  要校验的数据
 *
 *  @return YES:成功 NO:失败
 */
+(BOOL)baseCheckForRegEx:(NSString *)regEx data:(NSString *)data{
    
    NSPredicate *card = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regEx];
    
    if (([card evaluateWithObject:data])) {
        return YES;
    }
    return NO;
}

@end
